package com.example.android.dnd;

import android.content.ClipData;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class HoneyBeeView extends View {
	private TextView statusView;
	private TextView resultText;

	private final Bitmap honey = BitmapFactory.decodeResource(getContext()
			.getResources(), R.drawable.honeybee);

	public HoneyBeeView(Context context, AttributeSet attrs) {
		super(context, attrs);

		setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_MOVE) {
					ClipData data = ClipData.newPlainText("msg",
							"Please drop to robot.");
					v.startDrag(data, new DragShadowBuilder(v), null, 0);
					return true;
				}
				return false;
			}
		});

		setOnDragListener(new View.OnDragListener() {
			@Override
			public boolean onDrag(View v, DragEvent event) {
				if (event.getAction() == DragEvent.ACTION_DROP) {
					ClipData data = event.getClipData();
					for (int i = 0; i < data.getItemCount(); i++) {
						ClipData.Item item = data.getItemAt(i);
						Toast.makeText(getContext(),
								item.coerceToText(getContext()),
								Toast.LENGTH_SHORT).show();
					}
				} else if (event.getAction() == DragEvent.ACTION_DRAG_ENDED) {
					if (!event.getResult()) {
						resultText.setText("No drop");
					}
				}
				return false;
			}
		});
	}

	public void setTextView(TextView statusView, TextView resultText) {
		this.statusView = statusView;
		this.resultText = resultText;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		float x = (getWidth() - honey.getWidth()) / 2;
		float y = (getHeight() - honey.getHeight()) / 2;
		canvas.drawBitmap(honey, x, y, null);
	}

	@Override
	protected void onMeasure(int widthSpec, int heightSpec) {
		setMeasuredDimension(honey.getWidth(), honey.getHeight());
	}

	@Override
	public boolean onDragEvent(DragEvent event) {
		switch (event.getAction()) {
		case DragEvent.ACTION_DRAG_STARTED:
			statusView.setText("ACTION_DRAG_STARTED");
			resultText.setText(null);
			break;

		case DragEvent.ACTION_DRAG_ENDED:
			statusView.setText("ACTION_DRAG_ENDED");
			break;

		case DragEvent.ACTION_DRAG_LOCATION:
			statusView.setText("ACTION_DRAG_LOCATION");
			break;

		case DragEvent.ACTION_DROP:
			statusView.setText("ACTION_DROP");
			resultText.setText("Dropped on Honeycomb");
			break;

		case DragEvent.ACTION_DRAG_ENTERED:
			statusView.setText("ACTION_DRAG_ENTERED");
			break;

		case DragEvent.ACTION_DRAG_EXITED:
			statusView.setText("ACTION_DRAG_EXITED");
			break;
		}

		return true;
	}
}
